﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Xml;
using LorraineSec.DatabaseLib;

namespace LorraineSec.DatabaseLib.DataObjects
{
    public class Compartment : IComparable<Compartment>
    {
        #region Constants
        private const string ROOT_STR = XmlDatabase.COMPARTMENT;
        private const string ID_STR = XmlDatabase.ID;
        private const string NAME_STR = XmlDatabase.NAME;
        private const string PASS_STR = XmlDatabase.PASSCODE;
        #endregion

        private XmlNode xmlCompartmentRoot;
        private XmlNode xmlName;
        private XmlNode xmlPasscode;

        public Compartment(XmlNode node)
        {
            xmlCompartmentRoot = node;
            xmlName = xmlCompartmentRoot.SelectSingleNode(NAME_STR);
            xmlPasscode = xmlCompartmentRoot.SelectSingleNode(PASS_STR);
        }

        public static List<Compartment> GetList(XmlDatabase db)
        {
            List<Compartment> retList = new List<Compartment>();
            if (db.compartments != null)
            {
                XmlNodeList nodeList = db.compartments.SelectNodes(ROOT_STR);
                retList.Capacity = nodeList.Count;
                foreach (XmlNode n in nodeList)
                {
                    retList.Add((Compartment)n);
                }
            }
            return retList;
        }

        public static implicit operator Compartment(XmlNode node)
        {
            return new Compartment(node);
        }

        public static explicit operator XmlNode(Compartment u)
        {
            return u.xmlCompartmentRoot;
        }

        public uint ID
        {
            get { return UInt32.Parse(xmlCompartmentRoot.Attributes[ID_STR].Value); }
        }

        public string Name
        {
            get { return xmlName.InnerText; }
            set { xmlName.InnerText = value; }
        }

        public string Passcode
        {
            get { return xmlPasscode.InnerText; }
            set { xmlPasscode.InnerText = value; }
        }

        public override string ToString()
        {
            return Name;
        }

        public int CompareTo(Compartment other)
        {
            return (int)(this.ID - other.ID);
        }
    }
}
